# mahalMatch :: conducts mahalanobis matching on an adjusted covariate/treatment matrix.
#				 - performs a similar function call as mahalFun, except works outside genoud

mahalMatch=function(w,tr,mMat){
	options(warn=0)
	
	X=as.matrix(mMat) 
	chm=as.matrix(chol(var(X,na.rm=T)))
	n=nrow(X)
	k=ncol(X) 
	
	wM=matrix(0,k,k)
	diag(wM)=w
	SWS=t(chm)%*%wM%*%chm
	z=tr
	
	eps=.001		
	dMat=matrix(0,n,n)
	for(i in 1:n){
		if(i < n){
			dMat[i,(i+1):n]=mahalanobis(X[(i+1):n,],X[i,],cov=SWS,invert=T)/((z[i]-z[(i+1):n])^2+eps)
			dMat[(i+1):n,i]=dMat[i,(i+1):n]
		}
	}
		
	aMat=dMat+1
	
	zMat=matrix(NA,length(tr),length(tr))
	for(i in 1:length(tr)){
		zMat[i,]=abs(tr[i]-tr)
	}
	zMat[which(zMat==0)]=.00001	
	dMat=as.data.frame(as.matrix(aMat/zMat))		   	
	outs=nbpGreedy(dMat=dMat)
	   
	return(outs)
}
# end